import cv2
import numpy as np

def get_box(image):
    # 将图像转换为灰度图像
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 应用高斯模糊来减少噪声
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    max_val = np.max(blurred)
    # 使用Otsu's方法进行二值化
    _, binary = cv2.threshold(blurred, max_val/2, 255, cv2.THRESH_BINARY)
    # 形态学开运算去除噪声

    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
    opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
    # 找到轮廓
    contours, _ = cv2.findContours(opened, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # 如果找到轮廓，计算质心
    if contours:
        largest_contour = max(contours, key=cv2.contourArea)
        M = cv2.moments(largest_contour)
        if M["m00"] != 0:
            cx = int(M["m10"] / M["m00"])
            cy = int(M["m01"] / M["m00"])
        else:
            cx, cy = 0, 0
        centroid = (cx, cy)
        # 计算边界框
        x, y, w, h = cv2.boundingRect(largest_contour)
        p=10
        bbox = (x-p, y-p, w+2*p, h+2*p)
        # 在图像上绘制质心和边界框
        output_image = image.copy()
        cv2.circle(output_image, centroid, 5, (0, 255, 0), -1)
        x,y,w,h=bbox
        cv2.rectangle(output_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        print(f"亮点的中心位置: {centroid},亮点的边界框: {bbox}")
        return centroid,bbox,output_image
    else:
        return None


#  pyinstaller -F -c --uac-admin -n get_coor  ./get_coor.py
# Example usage:
if __name__=='__main__':
    src = cv2.imread(r'.\20240531_113524\Point01_0.jpg')
    cv2.imshow('src', src)
    img,_,bbox=get_box(src)
    cv2.imshow('img', img)
    cv2.waitKey()
